package com.scpii.universal.io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;

import com.scpii.universal.concurrent.Callback;

public class FileUtil {
	/**
	 * 保存文件
	 * 
	 * @param filePath
	 * @param resData
	 * @throws IOException
	 * @throws Exception
	 */
	public static void savefile(String filePath, byte[] resData,
			Callback callback, Map<Object, Object> data) throws IOException,
			Exception {

		File file = new File(filePath);
		File parentFile = file.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		if (!file.exists()) {
			file.createNewFile();
		}
		FileChannel fc = new RandomAccessFile(filePath, "rw").getChannel();
		MappedByteBuffer wr = fc.map(FileChannel.MapMode.READ_WRITE, 0,
				resData.length);
		wr.put(resData);
		fc.write(wr);
		fc.close();
		clean(wr, callback, data);
	}

	@SuppressWarnings("restriction")
	public static void clean(final Object buffer, Callback callback,
			Map<Object, Object> data) throws Exception {
		final Callback callbackFinal = callback;
		final Map<Object, Object> dataFinal = data;
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			public Object run() {
				try {
					java.lang.reflect.Method getCleanerMethod = buffer
							.getClass().getMethod("cleaner", new Class[0]);
					getCleanerMethod.setAccessible(true);
					sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod
							.invoke(buffer, new Object[0]);
					if (cleaner != null)
						cleaner.clean();
					if (callbackFinal != null)
						callbackFinal.handleMessage(dataFinal);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		});

	}
}
